"use client";

import { useEffect, useMemo, useState } from "react";
import { CheckCircleOutlined } from "@ant-design/icons";
import { Button, Radio, Space, message } from "antd";
import { userInfoAction, userInfoState } from "@/app/stores/userInfo.store";
import { useSnapshot } from "valtio";
import { userControllerUpdateUser } from "@/app/servers/api/user";

import { omit } from "lodash-es";

interface Question {
  questionText: string;
  optionA: string;
  optionB: string;
  optionC: string;
  optionD: string;
  correctOption: "A" | "B" | "C" | "D";
}

interface CoralClassParseJsonType
  extends Omit<API.ReturnCoralClass, "questionJson"> {
  questionJson: Question[];
}

export interface CoralClassDetailProps {
  classList: CoralClassParseJsonType[];
}

export default function CoralClassDetail({ classList }: CoralClassDetailProps) {
  const [courses] = useState<CoralClassParseJsonType[]>(classList);
  const [currentCourse, setCurrentCourse] = useState<CoralClassParseJsonType>(
    courses[0]
  );
  // 是否提交
  const [submitted, setSubmitted] = useState(false);
  // 已经回答的答案
  const [answers, setAnswers] = useState<number[]>([]);
  const userInfo = useSnapshot(userInfoState);
  useEffect(() => {
    // 请求用户列表
    userInfoAction.validateUserInfo();
  }, []);

  // 学习进度
  const learningProgress: string[] = useMemo(() => {
    if (!userInfo.learningProgress) {
      return [];
    }
    const result = JSON.parse(userInfo.learningProgress) || [];
    return result;
  }, [userInfo.learningProgress]);

  const isComplete = useMemo(() => {
    if (
      learningProgress &&
      learningProgress.includes(currentCourse.id.toString())
    ) {
      setSubmitted(true);
      setAnswers(
        currentCourse.questionJson.map((question) => {
          return ["A", "B", "C", "D"].findIndex(
            (option) => option === question.correctOption
          );
        })
      );
      return learningProgress.includes(currentCourse.id.toString());
    }
    return false;
  }, [learningProgress, currentCourse]);

  const handleAnswerChange = (questionIndex: number, value: number) => {
    setAnswers((prev) => {
      const newAnswers = [...prev];
      newAnswers[questionIndex] = value;
      return newAnswers;
    });
  };

  const handleSubmit = () => {
    if (answers.length !== currentCourse.questionJson.length) {
      message.error("请回答所有问题");
      return;
    }
    setSubmitted(true);
    message.success("提交成功");
    const result = omit(userInfo, [
      "avatarFile",
      "learningProgress",
      "articles",
      "actions",
      "comments",
      "password",
      "views",
    ]);
    const newLearingProgress = [
      ...learningProgress,
      currentCourse.id.toString(),
    ];
    userControllerUpdateUser({
      id: result.id!,
      learningProgress: JSON.stringify(newLearingProgress),
    });
  };

  return (
    <div className="container mx-auto px-4 py-8 flex gap-8">
      {/* 左侧课程列表 */}
      <div className="w-1/4">
        <h2 className="text-xl font-bold mb-4">课程列表</h2>
        <div className="space-y-2">
          {courses.map((course) => (
            <div
              key={course.id}
              className={`p-3 rounded cursor-pointer flex justify-between items-center ${
                currentCourse.id === course.id
                  ? "bg-blue-50 text-blue-600"
                  : "hover:bg-gray-50"
              }`}
              onClick={() => {
                setCurrentCourse(course);
                setAnswers([]);
                setSubmitted(false);
              }}
            >
              <span>{course.classTitle}</span>
              <CheckCircleOutlined
                className={
                  learningProgress.includes(course.id.toString())
                    ? "text-green-500"
                    : "text-gray-300"
                }
              />
            </div>
          ))}
        </div>
      </div>

      {/* 右侧课程内容 */}
      <div className="w-3/4">
        <h1 className="text-2xl font-bold mb-4">{currentCourse.classTitle}</h1>
        <p className="my-4">课程描述：{currentCourse.classDesc}</p>
        {/* 视频播放器 */}
        <div className="mb-8">
          <video
            width="100%"
            height="400px"
            src={currentCourse.video?.href}
            controls
          ></video>
        </div>
        {/* 课程作业 */}
        <div className="space-y-6">
          <h2 className="text-xl font-bold">课程作业</h2>
          {currentCourse?.questionJson?.map((question, index) => {
            const isCorrectAnswer =
              answers[index] ===
              ["A", "B", "C", "D"].findIndex(
                (option) => option === question.correctOption
              );
            const isGreen = isComplete || isCorrectAnswer;
            return (
              <div
                key={index}
                className={`p-4 border rounded ${
                  submitted
                    ? isGreen
                      ? "border-green-500"
                      : "border-red-500"
                    : "border-gray-200"
                }`}
              >
                <div
                  className={`font-medium mb-2 ${
                    submitted
                      ? isGreen
                        ? "text-green-600"
                        : "text-red-600"
                      : ""
                  }`}
                >
                  {index + 1}. {question.questionText}
                </div>
                <Radio.Group
                  onChange={(e) => handleAnswerChange(index, e.target.value)}
                  value={answers[index]}
                  disabled={submitted}
                >
                  <Space direction="vertical">
                    {[
                      question.optionA,
                      question.optionB,
                      question.optionC,
                      question.optionD,
                    ].map((option, optionIndex) => (
                      <Radio
                        key={optionIndex}
                        value={optionIndex}
                        className={
                          submitted
                            ? option === question.correctOption
                              ? isGreen
                                ? "text-green-600"
                                : "text-red-600"
                              : ""
                            : ""
                        }
                      >
                        {String.fromCharCode(65 + optionIndex)}. {option}
                      </Radio>
                    ))}
                  </Space>
                </Radio.Group>
              </div>
            );
          })}
        </div>

        {/* 提交按钮 */}
        <div className="mt-8">
          {!isComplete && (
            <Button type="primary" size="large" onClick={handleSubmit}>
              提交答案
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}
